<!-- 搜索框 -->
<template>
  <div>
    <div class="search">
        <input type="text" class="search-Input" v-model="keyword" placeholder="输入城市名或拼音"/>
    </div>
    <div class="search-content" ref="wrapper" v-show="keyword">
      <ul>
        <li v-for="item in list" :key="item.id" class="search-item border-bottom" @click="handleCityChange(item.name)">{{item.name}}</li>
        <li class="search-item border-bottom" v-show=" hasNoData">没有找到片匹配数据</li>
      </ul>
    </div>
  </div>

</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },

  components: {},

  computed: {
    hasNoData () {
      return !this.list.length
    }
  },

  props: {
    cities: Object
  },

  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        return
      }
      this.timer = setTimeout(() => {
        var result = []
        for (var i in this.cities) {
          this.cities[i].forEach(element => {
            if (element.spell.indexOf(this.keyword) > -1 || element.name.indexOf(this.keyword) > -1) {
              result.push(element)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },

  methods: {
    handleCityChange (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },

  mounted () {
    this.scroll = new Bscroll(this.$refs.wrapper)
  }

}

</script>
<style lang='stylus' scoped>
@import '~styles/varibles.styl'
.search
    height .72rem
    background-color $bgcolor
    padding 0 .1rem
    .search-Input
        box-sizing border-box
        width 100%
        height 0.6rem
        line-height .6rem
        text-align center
        border-radius .06rem
        color #666
        padding 0 .1rem
.search-content
  overflow hidden
  position absolute
  top 1.58rem
  left 0
  right 0
  bottom 0
  background-color #ccc
  z-index 999
  .search-item
    height .62rem
    line-height .62rem
    padding-left .2rem
    color #666
    background-color #fff
</style>
